﻿using Microsoft.Extensions.Primitives;
using System.Diagnostics;

namespace ApiMiddleware.Middleware
{
    public class RequestHeaderVerificationMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        /// <summary>
        /// 计时器
        /// </summary>
        private Stopwatch _stopwatch;
        private const string RESPONSE_HEADER_RESPONSE_TIME = "X-Response-Time-ms";

        public RequestHeaderVerificationMiddleware(RequestDelegate next, ILogger<RequestHeaderVerificationMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            _stopwatch = new Stopwatch();
            _stopwatch.Start();
            _logger.LogError($"Handling request: {context.Request.Path}");

            StringValues token = "";
            context.Request.Headers.TryGetValue("token", out token);
            //获取到请求头中的 token 数据

            //if (!context.Request.Headers.TryGetValue("request_id", out String Values request_id) || string.IsNullOrEmpty(request_id))
            //{
            //    await HandleMessage(context, JsonConvert.SerializeObject(new { msg = "request_id不可为空", request_id = request_id }));
            //    goto step;
            //}
            //if (!context.Request.Headers.TryGetValue("uname", out StringValues uname) || string.IsNullOrEmpty(uname))
            //{
            //    await HandleMessage(context, JsonConvert.SerializeObject(new { msg = "名称不可为空", request_id = request_id, uname = uname }));
            //    goto step;
            //}


            context.Response.OnStarting(() =>
            {
                // Stop the timer information and calculate the time  
                _stopwatch.Stop();
                var responseTimeForCompleteRequest = _stopwatch.ElapsedMilliseconds;
                // Add the Response time information in the Response headers.  
                context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME] = responseTimeForCompleteRequest.ToString();
                return Task.CompletedTask;
            });

            if (!context.Response.HasStarted)
            {
                await _next(context);
            }
        }


    }
}